//
//  CustomWebViewController.m
//  Peso Guide
//
//  Created by macbook on 2025/6/6.
//

#import "CustomWebViewController.h"
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "DeviceModelUtil.h"
#import "ProductDetailViewController.h"
#import "MineSettingViewController.h"
#import "MineViewController.h"
#import <StoreKit/StoreKit.h>
#import "ProductDetailViewController.h"

@interface CustomWebViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *webView;
@property (strong, nonatomic) UIProgressView *progressView;

@property (nonatomic, strong) NSString *startTime;
@property (nonatomic, strong) NSString *endTime;

@property (nonatomic, strong) NSString *lng;
@property (nonatomic, strong) NSString *lat;

@end

@implementation CustomWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navView.backgroundColor = ColorHex(@"#1A7A35");
    self.backColor = ColorHex(@"#FFFFFF");
    self.backButton.hidden = YES;
    
    UIButton *backButton = [PesoKit createButtonWithFrame:CGRectMake(12, self.navView.height-13-20, 20, 20) backGroundColor:[UIColor clearColor] title:@"" titleColor:[UIColor clearColor] font:[UIFont systemFontOfSize:12]];
    [backButton setBackgroundImage:[UIImage imageNamed:@"ic_backBtn_white"] forState:0];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    [self.navView addSubview:backButton];
    
    self.startTime = [DataPointManager getCurrentTimestamp];
        
    [[LocationManager sharedManager] getCurrentLocationWithSuccess:^(CLLocationCoordinate2D coordinate) {
        DLog(@"get location success：log=%f, lat=%f", coordinate.longitude, coordinate.latitude);
        
        self.lng = [NSString stringWithFormat:@"%f",coordinate.longitude];
        self.lat = [NSString stringWithFormat:@"%f",coordinate.latitude];

        // 使用获取到的经纬度做其他操作...
        
    } failure:^(NSError *error) {
        // 处理错误情况...
    }];
    
    [self createUI];
    [self request];
    [self setupProgressView];
    
    if (self.backRoot == YES) {
        NSMutableArray *navs = [NSMutableArray safeArrayWithArray:self.navigationController.viewControllers];
        for (UIViewController *vc in self.navigationController.viewControllers) {
            if ([vc isKindOfClass:[ProductDetailViewController class]]) {
                [navs removeObject:vc];
                break;
            }
        }
        self.navigationController.viewControllers = navs;
    }
}

- (void)goBack {
    if (self.isPresent == YES) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }else {
        if (self.webView.canGoBack) {
            [self.webView goBack];
        }else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

#pragma mark - Request
- (void)request {
    
    NSString *url = @"";
    
    if ([self.linkUrl hasPrefix:@"?"]) {
        url = [NSString stringWithFormat:@"%@&overhead=%@&locations=%@&relative=%@&immediately=%@&mitigate=%@&techniques=%@&narrowly=%@",self.linkUrl,[NSString stringWithFormat:@"%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]],[DeviceModelUtil deviceMarketingName],[AppTools getOrCreatePseudoIDFV],[NSString stringWithFormat:@"%@",[[UIDevice currentDevice] systemVersion]],[AppTools getLoginToken],[AppTools getIDFA],[AppTools getLoginCountry]];
    } else {
        url = [NSString stringWithFormat:@"%@?overhead=%@&locations=%@&relative=%@&immediately=%@&mitigate=%@&techniques=%@&narrowly=%@",self.linkUrl,[NSString stringWithFormat:@"%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]],[DeviceModelUtil deviceMarketingName],[AppTools getOrCreatePseudoIDFV],[NSString stringWithFormat:@"%@",[[UIDevice currentDevice] systemVersion]],[AppTools getLoginToken],[AppTools getIDFA],[AppTools getLoginCountry]];
    }
        
    NSCharacterSet *allowedCharacterSet = [NSCharacterSet URLQueryAllowedCharacterSet];
    NSString *escapedString = [url stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
    DLog(@"转义后的URL: %@", escapedString);
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:escapedString]]];
}

#pragma mark - CreateUI
- (void)createUI {
    
    NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    config.preferences = preferences;
    config.userContentController = wkUController;
    config.allowsInlineMediaPlayback = YES;
    config.mediaTypesRequiringUserActionForPlayback = false;
    
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, kStarBarHeight, KScreenWidth, KScreenHeight-kStarBarHeight) configuration:config];
    _webView.UIDelegate = self;
    _webView.allowsBackForwardNavigationGestures = YES;
    _webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"saveAsImage"];
    [self.view addSubview:_webView];
    
    [_webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable title, NSError * _Nullable error) {
        if (![AppTools isEmpty:title]) {
            self.titleLabel.text = title;
        }else {
            self.titleLabel.text = [self getAppName];
        }
    }];
    
    [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    [_webView addObserver:self
               forKeyPath:@"estimatedProgress"
                  options:NSKeyValueObservingOptionNew
                  context:nil];
    
    // 添加所有需要监听的方法
    NSArray *methods = @[
        @"SearchingExtent",
        @"InStraightforward",
        @"ArticleFunctions",
        @"AlsoRemove",
        @"ByFunctions",
        @"WithArticle",
        @"DefinitionKnown",
        @"NameIn",
        @"FromWith",
        @"CanAs",
        @"InIs"
    ];
    
    for (NSString *method in methods) {
        [wkUController addScriptMessageHandler:self name:method];
        
    }
    config.userContentController = wkUController;
}

- (void)setupProgressView {
    // 创建底部进度条
    self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
    self.progressView.trackTintColor = [UIColor whiteColor];
    self.progressView.progressTintColor = ColorHex(@"#1A7A35");
    
    // 设置位置在底部
    self.progressView.frame = CGRectMake(0, kStarBarHeight, KScreenWidth, 5.0f);
    self.progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    
    [self.view addSubview:self.progressView];
}


#pragma mark KVO 实现方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"title"]) {
        if (object == self.webView) {
            self.titleLabel.text = self.webView.title;
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
            // 更新进度条
            [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
            // 加载完成时隐藏进度条
            if (self.webView.estimatedProgress >= 1.0) {
                [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                    self.progressView.alpha = 0.0;
                } completion:^(BOOL finished) {
                    self.progressView.hidden = YES;
                    [self.progressView setProgress:0.0 animated:NO];
                }];
            } else {
                self.progressView.hidden = NO;
                self.progressView.alpha = 1.0;
            }
        }
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    // 开始加载时显示进度条
    self.progressView.hidden = NO;
    self.progressView.alpha = 1.0;
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    // 加载失败时隐藏进度条
    [UIView animateWithDuration:0.3 animations:^{
        self.progressView.alpha = 0.0;
    } completion:^(BOOL finished) {
        self.progressView.hidden = YES;
        [self.progressView setProgress:0.0 animated:NO];
    }];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    // 页面加载完成之后调用
}

#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    DLog(@"message.name---=====-----%@",message.name);
    // 根据不同的方法名处理不同的操作
    if ([message.name isEqualToString:@"SearchingExtent"]) {
        [self handleSearchingExtent:message.body];
    }
    else if ([message.name isEqualToString:@"InStraightforward"]) {
        [self handleInStraightforward];
    }
    else if ([message.name isEqualToString:@"ArticleFunctions"]) {
        [self handleArticleFunctions:message.body];
    }
    else if ([message.name isEqualToString:@"AlsoRemove"]) {
        [self handleAlsoRemove];
    }
    else if ([message.name isEqualToString:@"ByFunctions"]) {
        [self handleByFunctions];
    }
    else if ([message.name isEqualToString:@"WithArticle"]) {
        [self handleWithArticle];
    }
    else if ([message.name isEqualToString:@"DefinitionKnown"]) {
        [self handleDefinitionKnown:message.body];
    }
    else if ([message.name isEqualToString:@"NameIn"]) {
        [self handleNameIn];
    }
    else if ([message.name isEqualToString:@"FromWith"]) {
        [self handleFromWith:message.body];
    }
    else if ([message.name isEqualToString:@"CanAs"]) {
        [self handleCanAs];
    }
    else if ([message.name isEqualToString:@"InIs"]) {
        [self handleInIs];
    }
}

// 页面跳转
- (void)handleSearchingExtent:(id)body {
    if ([body isKindOfClass:[NSString class]]) {
        NSString *recent = (NSString *)body;
        [self pushVC:recent];
    }else if ([body isKindOfClass:[NSArray class]]) {
        NSString *recent = [body safeObjectAtIndex:0];
        [self pushVC:recent];
    }
}

- (void)pushVC:(NSString *)recent {
    if ([recent rangeOfString:@"http://"].location != NSNotFound ||
        [recent rangeOfString:@"https://"].location != NSNotFound) {
        //webView
        dispatch_async(dispatch_get_main_queue(), ^{
            CustomWebViewController *webVC = [[CustomWebViewController alloc] init];
            webVC.linkUrl = recent;
            [[AppTools getCurrentVC].navigationController pushViewController:webVC animated:YES];
            return;
        });
    }
    if ([recent rangeOfString:@"pe://so.gui.de/thelike"].location != NSNotFound) {
        //设置
        MineSettingViewController *settingVC = [[MineSettingViewController alloc] init];
        settingVC.hidesBottomBarWhenPushed = YES;
        [[AppTools getCurrentVC].navigationController pushViewController:settingVC animated:YES];
        return;
    }
    if ([recent rangeOfString:@"pe://so.gui.de/andlove"].location != NSNotFound) {
        //首页
        dispatch_async(dispatch_get_main_queue(), ^{
            [AppTools getCurrentVC].tabBarController.selectedIndex = 0;
            return;
        });
    }
    if ([recent rangeOfString:@"pe://so.gui.de/standard"].location != NSNotFound) {
        //登录
        dispatch_async(dispatch_get_main_queue(), ^{
            [AppTools toLogin];
            return;
        });
    }
    if ([recent rangeOfString:@"pe://so.gui.de/classes"].location != NSNotFound) {
        //订单
        dispatch_async(dispatch_get_main_queue(), ^{
            [AppTools getCurrentVC].tabBarController.selectedIndex = 1;
            return;
        });
    }
    if ([recent rangeOfString:@"pe://so.gui.de/islove"].location != NSNotFound) {
        //产品详情
        dispatch_async(dispatch_get_main_queue(), ^{
            NSArray *array = [recent componentsSeparatedByString:@"="];
            NSString *theId = [NSString stringWithFormat:@"%@",[array safeObjectAtIndex:1]];
            ProductDetailViewController *vc = [[ProductDetailViewController alloc] init];
            vc.productId = theId;
            vc.hidesBottomBarWhenPushed = YES;
            [[AppTools getCurrentVC].navigationController pushViewController:vc animated:YES];
            return;
        });
    }
}

// 关闭当前WebView
- (void)handleInStraightforward {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}

// 带参数页面跳转
- (void)handleArticleFunctions:(id)body {
    if ([body isKindOfClass:[NSDictionary class]]) {
        NSDictionary *params = (NSDictionary *)body;
        NSString *recent = params[@"url"];
        
        [self pushVC:recent];
        
    }else if ([body isKindOfClass:[NSString class]]) {
        NSString *recent = (NSString *)body;
        [self pushVC:recent];
    }else if ([body isKindOfClass:[NSArray class]]) {
        NSString *recent = [body safeObjectAtIndex:0];
        [self pushVC:recent];
    }
}

// 回到首页并关闭当前页
- (void)handleAlsoRemove {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController popToRootViewControllerAnimated:YES];
    });
}

// 回到个人中心并关闭当前页
- (void)handleByFunctions {
    dispatch_async(dispatch_get_main_queue(), ^{
        for (UIViewController *vc in self.navigationController.viewControllers) {
            if ([vc isKindOfClass:[MineViewController class]]) {
                [self.navigationController popToViewController:vc animated:YES];
                return;
            }
        }
        
        // 如果没找到，回到首页
        [self.navigationController popToRootViewControllerAnimated:YES];
    });
}

// 跳转到登录页并清空页面栈
- (void)handleWithArticle {
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"user_token"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [AppTools toLogin];
    });
}

// 拨打电话号码
- (void)handleDefinitionKnown:(id)body {
    if ([body isKindOfClass:[NSString class]]) {
        NSString *phone = (NSString *)body;
        NSString *phoneNumber = [@"tel:" stringByAppendingString:phone];
        NSURL *phoneURL = [NSURL URLWithString:phoneNumber];
        
        if (phoneURL && [[UIApplication sharedApplication] canOpenURL:phoneURL]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[UIApplication sharedApplication] openURL:phoneURL options:@{} completionHandler:nil];
            });
        }
    }
}

// App Store评分
- (void)handleNameIn {
    // 替换为你的App Store ID
    if (@available(iOS 10.3, *)) {
        // 使用系统提供的评价弹窗（有次数限制）
        [SKStoreReviewController requestReview];
    } else {
        // 旧版本系统跳转到App Store
        [self openAppStoreReviewPage];
    }
}

// 跳转到App Store评价页面的方法
- (void)openAppStoreReviewPage {
    // 替换 YOUR_APP_ID 为你的应用ID（数字形式）
    NSString *appID = @"YOUR_APP_ID";
    NSString *reviewURL = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@?action=write-review", appID];
    
    NSURL *url = [NSURL URLWithString:reviewURL];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

// 确认申请埋点
- (void)handleFromWith:(id)body {
    NSString *time = [DataPointManager getCurrentTimestamp];
    
    if ([body isKindOfClass:[NSString class]]) {
        NSString *theId = (NSString *)body;
        dispatch_async(dispatch_get_main_queue(), ^{
            [[DataPointManager sharedManager] senRequestWithType:@"10" startTime:time endTime:time lng:self.lng lat:self.lat orderId:theId];
//            [[DataPointManager sharedManager] logEventWithType:@"10" startTime:self.startTime endTime:self.endTime orderId:theId];
        });
    }else if ([body isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = (NSDictionary *)body;
        NSString *orderId = [NSString stringWithFormat:@"%@",[dic safeObjectForKey:@"distress"]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [[DataPointManager sharedManager] senRequestWithType:@"10" startTime:time endTime:time lng:self.lng lat:self.lat orderId:orderId];
//            [[DataPointManager sharedManager] logEventWithType:@"10" startTime:self.startTime endTime:self.endTime orderId:[AppTools isEmpty:orderId]?@"":orderId];
        });
    }else if ([body isKindOfClass:[NSArray class]]) {
        NSArray *array = (NSArray *)body;
        NSString *orderId = [NSString stringWithFormat:@"%@",[array safeObjectAtIndex:0]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [[DataPointManager sharedManager] senRequestWithType:@"10" startTime:time endTime:time lng:self.lng lat:self.lat orderId:orderId];
//            [[DataPointManager sharedManager] logEventWithType:@"10" startTime:self.startTime endTime:self.endTime orderId:[AppTools isEmpty:orderId]?@"":orderId];
        });
    }else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[DataPointManager sharedManager] senRequestWithType:@"10" startTime:time endTime:time lng:self.lng lat:self.lat orderId:@""];
//            [[DataPointManager sharedManager] logEventWithType:@"10" startTime:self.startTime endTime:self.endTime orderId:@""];
        });
    }
}

// 开始绑卡时间
- (void)handleCanAs {
    // 记录绑卡开始时间
    self.startTime = [DataPointManager getCurrentTimestamp];
}

// 结束绑卡时间
- (void)handleInIs {
    
    self.endTime = [DataPointManager getCurrentTimestamp];
    
    [[DataPointManager sharedManager] senRequestWithType:@"8" startTime:self.startTime endTime:self.endTime lng:self.lng lat:self.lat orderId:@""];

//    [[DataPointManager sharedManager] logEventWithType:@"8" startTime:self.startTime endTime:self.endTime orderId:@""];
}


- (NSString*)getAppName {
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *appName = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
    if (!appName) {
        appName = [bundle objectForInfoDictionaryKey:@"CFBundleName"];
    }
    return appName;
}

#pragma mark - 内存管理和清理

- (void)dealloc {
    // 移除所有消息处理器
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView.configuration.userContentController removeAllUserScripts];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"SearchingExtent"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"InStraightforward"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"ArticleFunctions"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"AlsoRemove"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"ByFunctions"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"WithArticle"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"DefinitionKnown"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"NameIn"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"FromWith"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"CanAs"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"InIs"];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
